Node.js DiffieHellman Reference

Node.js இல் பாதுகாப்பான விசை பரிமாற்ற நெறிமுறையைப் பயன்படுத்துவதற்கான முழுமையான வழிகாட்டி

DiffieHellman Object

DiffieHellman வகுப்பு Node.js இன் crypto தொகுதியின் ஒரு பகுதியாகும். இது Diffie-Hellman விசை பரிமாற்ற நெறிமுறையை செயல்படுத்துகிறது, இது இரண்டு தரப்பினரும் பாதுகாப்பற்ற சேனலில் பகிரப்பட்ட ரகசியத்தைப் பாதுகாப்பாக நிறுவ அனுமதிக்கிறது.

Import Crypto Module

// Import the crypto module
const crypto = require('crypto');

// Create a DiffieHellman instance
const dh = crypto.createDiffieHellman(2048); // 2048-bit prime length

DiffieHellman Methods

முறை விளக்கம்
dh.generateKeys([encoding]) தனிப்பட்ட மற்றும் பொது Diffie-Hellman விசை மதிப்புகளை உருவாக்குகிறது. encoding வழங்கப்பட்டால், ஒரு சரம் திரும்பும்; இல்லையெனில், ஒரு Buffer திரும்பும்.
dh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding]) மற்ற தரப்பின் பொது விசையைப் பயன்படுத்தி பகிரப்பட்ட ரகசியத்தைக் கணக்கிடுகிறது. inputEncoding வழங்கப்பட்டால், otherPublicKey ஒரு சரமாக எதிர்பார்க்கப்படுகிறது; இல்லையெனில், ஒரு Buffer, TypedArray, அல்லது DataView. outputEncoding வழங்கப்பட்டால், ஒரு சரம் திரும்பும்; இல்லையெனில், ஒரு Buffer திரும்பும்.
dh.getPrime([encoding]) Diffie-Hellman முதன்மையைத் திரும்பப் பெறுகிறது. encoding வழங்கப்பட்டால், ஒரு சரம் திரும்பும்; இல்லையெனில், ஒரு Buffer திரும்பும்.
dh.getGenerator([encoding]) Diffie-Hellman ஜெனரேட்டரைத் திரும்பப் பெறுகிறது. encoding வழங்கப்பட்டால், ஒரு சரம் திரும்பும்; இல்லையெனில், ஒரு Buffer திரும்பும்.
dh.getPublicKey([encoding]) Diffie-Hellman பொது விசையைத் திரும்பப் பெறுகிறது. encoding வழங்கப்பட்டால், ஒரு சரம் திரும்பும்; இல்லையெனில், ஒரு Buffer திரும்பும்.
dh.getPrivateKey([encoding]) Diffie-Hellman தனிப்பட்ட விசையைத் திரும்பப் பெறுகிறது. encoding வழங்கப்பட்டால், ஒரு சரம் திரும்பும்; இல்லையெனில், ஒரு Buffer திரும்பும்.
dh.setPublicKey(publicKey[, encoding]) Diffie-Hellman பொது விசையை அமைக்கிறது. encoding வழங்கப்பட்டால், publicKey ஒரு சரமாக எதிர்பார்க்கப்படுகிறது; இல்லையெனில், ஒரு Buffer, TypedArray, அல்லது DataView.
dh.setPrivateKey(privateKey[, encoding]) Diffie-Hellman தனிப்பட்ட விசையை அமைக்கிறது. encoding வழங்கப்பட்டால், privateKey ஒரு சரமாக எதிர்பார்க்கப்படுகிறது; இல்லையெனில், ஒரு Buffer, TypedArray, அல்லது DataView.
dh.verifyError துவக்க அல்லது சரிபார்ப்பு சோதனைகளின் போது ஏற்பட்ட எந்தவொரு பிழைகளையும் குறிக்கும் கொடிகளின் பிட் புலம்.

Creating DiffieHellman Instances

DiffieHellman நிகழ்வை உருவாக்க பல வழிகள் உள்ளன:

const crypto = require('crypto');

// Method 1: Generate a new DH group with specified prime length
const dh1 = crypto.createDiffieHellman(2048);
console.log('Generated prime length:', dh1.getPrime().length * 8, 'bits');

// Method 2: Create a DH group using a predefined prime
const prime = Buffer.from('prime-number-in-hex', 'hex');
const dh2 = crypto.createDiffieHellman(prime);

// Method 3: Create a DH group using a predefined prime and generator
const generator = Buffer.from('02', 'hex'); // Often 2, 5, or other small values
const dh3 = crypto.createDiffieHellman(prime, generator);

// Method 4: Using predefined groups with getDiffieHellman()
const predefinedGroupName = 'modp14'; // RFC 3526 2048-bit MODP Group
const dh4 = crypto.getDiffieHellman(predefinedGroupName);

getDiffieHellman() முறை பின்வரும் முன்கட்டுப்படுத்தப்பட்ட குழுக்களை ஆதரிக்கிறது:

குழு பெயர் விளக்கம் அளவு
modp1 RFC 2409 768-bit MODP Group 768 bits
modp2 RFC 2409 1024-bit MODP Group 1024 bits
modp5 RFC 3526 1536-bit MODP Group 1536 bits
modp14 RFC 3526 2048-bit MODP Group 2048 bits
modp15 RFC 3526 3072-bit MODP Group 3072 bits
modp16 RFC 3526 4096-bit MODP Group 4096 bits
modp17 RFC 3526 6144-bit MODP Group 6144 bits
modp18 RFC 3526 8192-bit MODP Group 8192 bits

Basic Key Exchange Example

பின்வரும் எடுத்துக்காட்டு இரண்டு தரப்பினருக்கு இடையே (Alice மற்றும் Bob) அடிப்படை Diffie-Hellman விசை பரிமாற்றத்தை விளக்குகிறது:

const crypto = require('crypto');

// Alice generates parameters and keys
console.log('Alice: Creating DiffieHellman instance...');
const alice = crypto.createDiffieHellman(2048);
const aliceKeys = alice.generateKeys();

// Bob also needs parameters from Alice
console.log('Alice: Sending parameters to Bob...');
const p = alice.getPrime();
const g = alice.getGenerator();

// Bob creates a DiffieHellman instance with the same parameters
console.log('Bob: Creating DiffieHellman instance with Alice\'s parameters...');
const bob = crypto.createDiffieHellman(p, g);
const bobKeys = bob.generateKeys();

// Exchange public keys (over an insecure channel)
console.log('Exchanging public keys...');
const alicePublicKey = alice.getPublicKey();
const bobPublicKey = bob.getPublicKey();

// Alice computes the shared secret using Bob's public key
console.log('Alice: Computing shared secret...');
const aliceSecret = alice.computeSecret(bobPublicKey);

// Bob computes the shared secret using Alice's public key
console.log('Bob: Computing shared secret...');
const bobSecret = bob.computeSecret(alicePublicKey);

// Both secrets should be the same
console.log('Alice\'s secret:', aliceSecret.toString('hex'));
console.log('Bob\'s secret:', bobSecret.toString('hex'));
console.log('Do they match?', aliceSecret.equals(bobSecret));

// This shared secret can now be used as a key for symmetric encryption

Using Predefined Groups

தரப்படுத்தப்பட்ட பயன்பாடுகளுக்கு, முன்கட்டுப்படுத்தப்பட்ட குழுக்களைப் பயன்படுத்துவது பொருந்தக்கூடிய தன்மையை உறுதிப்படுத்தும்:

const crypto = require('crypto');

// Using the RFC 3526 MODP Group 14 (2048 bits)
console.log('Alice: Creating DiffieHellman using predefined group...');
const alice = crypto.getDiffieHellman('modp14');
alice.generateKeys();

// Bob also uses the same predefined group
console.log('Bob: Creating DiffieHellman using predefined group...');
const bob = crypto.getDiffieHellman('modp14');
bob.generateKeys();

// Exchange public keys (over an insecure channel)
console.log('Exchanging public keys...');
const alicePublicKey = alice.getPublicKey();
const bobPublicKey = bob.getPublicKey();

// Compute shared secrets
const aliceSecret = alice.computeSecret(bobPublicKey);
const bobSecret = bob.computeSecret(alicePublicKey);

// Verify that the shared secrets match
console.log('Do the shared secrets match?', aliceSecret.equals(bobSecret));

// Output information about the group
console.log('Group prime size:', alice.getPrime().length * 8, 'bits');
console.log('Generator value:', alice.getGenerator().toString('hex'));

Diffie-Hellman with Encryption

இந்த எடுத்துக்காட்டு AES குறியாக்கத்திற்கான பகிரப்பட்ட விசையை நிறுவ Diffie-Hellman ஐப் பயன்படுத்துவதன் முழுமையான காட்சியைக் காட்டுகிறது:

const crypto = require('crypto');

// Create DiffieHellman instances for Alice and Bob
const alice = crypto.createDiffieHellman(2048);
alice.generateKeys();

// Bob uses Alice's parameters
const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());
bob.generateKeys();

// Exchange public keys
const alicePublicKey = alice.getPublicKey();
const bobPublicKey = bob.getPublicKey();

// Compute shared secrets
const aliceSecret = alice.computeSecret(bobPublicKey);
const bobSecret = bob.computeSecret(alicePublicKey);

// Use the shared secret as a key for encryption
// First, derive a suitable key using a hash function
function deriveKey(secret, salt, keyLength) {
  return crypto.pbkdf2Sync(secret, salt, 1000, keyLength, 'sha256');
}

// Alice sends an encrypted message to Bob
function encrypt(text, secret) {
  // Create a salt and derive a key
  const salt = crypto.randomBytes(16);
  const key = deriveKey(secret, salt, 32); // 32 bytes for AES-256
  const iv = crypto.randomBytes(16);
  
  // Encrypt the message
  const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  
  // Return everything Bob needs to decrypt
  return {
    salt: salt.toString('hex'),
    iv: iv.toString('hex'),
    encrypted
  };
}

// Bob decrypts the message from Alice
function decrypt(encryptedInfo, secret) {
  // Parse values
  const salt = Buffer.from(encryptedInfo.salt, 'hex');
  const iv = Buffer.from(encryptedInfo.iv, 'hex');
  const encrypted = encryptedInfo.encrypted;
  
  // Derive the same key
  const key = deriveKey(secret, salt, 32);
  
  // Decrypt the message
  const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  
  return decrypted;
}

// Alice encrypts a message using the shared secret
const message = 'Hello Bob, this is a secret message from Alice!';
console.log('Original message:', message);

const encryptedMessage = encrypt(message, aliceSecret);
console.log('Encrypted message:', encryptedMessage);

// Bob decrypts the message using his shared secret
const decryptedMessage = decrypt(encryptedMessage, bobSecret);
console.log('Decrypted message:', decryptedMessage);

Working with Custom Parameters

Diffie-Hellman க்கு குறிப்பிட்ட அளவுருக்கள் தேவைப்படும் போது:

const crypto = require('crypto');

// Custom prime and generator values
// These would normally be carefully chosen for security
const primeHex = `
  ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74
  020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f1437
  4fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed
  ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf05
  98da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb
  9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3b
  e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf695581718
  3995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff
`.replace(/\s+/g, '');

const prime = Buffer.from(primeHex, 'hex');
const generator = Buffer.from('02', 'hex');

// Create DiffieHellman with custom parameters
const dh = crypto.createDiffieHellman(prime, generator);

// Generate keys
dh.generateKeys();

// Verify the parameters
console.log('Using custom prime of length:', prime.length * 8, 'bits');
console.log('Generator:', generator.toString('hex'));

// Validation
console.log('Verify error code:', dh.verifyError);
if (dh.verifyError) {
  console.error('The parameters did not pass validation!');
} else {
  console.log('The parameters passed validation.');
}

// Output public and private keys
console.log('Public key length:', dh.getPublicKey().length * 8, 'bits');
console.log('Private key length:', dh.getPrivateKey().length * 8, 'bits');

Key Generation with Specific Encoding

DiffieHellman விசைகளுடன் பணிபுரியும் போது நீங்கள் குறியீடுகளைக் குறிப்பிடலாம்:

const crypto = require('crypto');

// Create DiffieHellman instance
const dh = crypto.createDiffieHellman(1024);

// Generate keys
dh.generateKeys();

// Get keys and parameters with different encodings
console.log('With Buffer (default):');
console.log('  - Prime:', dh.getPrime());
console.log('  - Generator:', dh.getGenerator());
console.log('  - Public Key:', dh.getPublicKey());
console.log('  - Private Key:', dh.getPrivateKey());

console.log('\nWith hex encoding:');
console.log('  - Prime:', dh.getPrime('hex'));
console.log('  - Generator:', dh.getGenerator('hex'));
console.log('  - Public Key:', dh.getPublicKey('hex'));
console.log('  - Private Key:', dh.getPrivateKey('hex'));

console.log('\nWith base64 encoding:');
console.log('  - Prime:', dh.getPrime('base64'));
console.log('  - Generator:', dh.getGenerator('base64'));
console.log('  - Public Key:', dh.getPublicKey('base64'));
console.log('  - Private Key:', dh.getPrivateKey('base64'));

// Set keys using specific encoding
const newPublicKey = crypto.randomBytes(dh.getPrime().length - 10);
dh.setPublicKey(newPublicKey);
console.log('\nAfter setting new public key:');
console.log('  - Public Key (hex):', dh.getPublicKey('hex'));

Error Handling

கிரிப்டோகிராஃபிக் செயல்பாடுகளுடன் பணிபுரியும் போது பிழை கையாளுதல் முக்கியமானது:

const crypto = require('crypto');

// Function to safely create DiffieHellman
function createDHSafely(options) {
  try {
    let dh;
    
    if (typeof options === 'number') {
      // Create with prime length
      dh = crypto.createDiffieHellman(options);
    } else if (options.group) {
      // Create with predefined group
      dh = crypto.getDiffieHellman(options.group);
    } else if (options.prime) {
      // Create with custom prime and optional generator
      const prime = Buffer.from(options.prime, options.encoding || 'hex');
      const generator = options.generator ?
        Buffer.from(options.generator, options.encoding || 'hex') :
        undefined;
      
      dh = generator ?
        crypto.createDiffieHellman(prime, generator) :
        crypto.createDiffieHellman(prime);
    } else {
      throw new Error('Invalid options for DiffieHellman creation');
    }
    
    // Check for errors
    if (dh.verifyError) {
      const errors = [];
      // Check specific error flags
      if (dh.verifyError & crypto.constants.DH_CHECK_P_NOT_SAFE_PRIME)
        errors.push('DH_CHECK_P_NOT_SAFE_PRIME');
      if (dh.verifyError & crypto.constants.DH_CHECK_P_NOT_PRIME)
        errors.push('DH_CHECK_P_NOT_PRIME');
      if (dh.verifyError & crypto.constants.DH_UNABLE_TO_CHECK_GENERATOR)
        errors.push('DH_UNABLE_TO_CHECK_GENERATOR');
      if (dh.verifyError & crypto.constants.DH_NOT_SUITABLE_GENERATOR)
        errors.push('DH_NOT_SUITABLE_GENERATOR');
      
      throw new Error(`DiffieHellman parameter validation failed: ${errors.join(', ')}`);
    }
    
    return dh;
  } catch (error) {
    console.error('Error creating DiffieHellman instance:', error.message);
    throw error;
  }
}

// Test with valid options
try {
  const dh1 = createDHSafely(2048);
  console.log('Successfully created DH with 2048-bit prime');
  
  const dh2 = createDHSafely({ group: 'modp14' });
  console.log('Successfully created DH with predefined group modp14');
} catch (error) {
  console.error('Error in valid tests:', error.message);
}

// Test with invalid options
try {
  // Invalid prime value
  const invalidPrime = '12345'; // Too short, not a prime
  const dh3 = createDHSafely({
    prime: invalidPrime,
    encoding: 'hex'
  });
} catch (error) {
  console.error('Expected error with invalid prime:', error.message);
}

try {
  // Invalid group name
  const dh4 = createDHSafely({ group: 'nonexistent-group' });
} catch (error) {
  console.error('Expected error with invalid group:', error.message);
}

Security Considerations

Diffie-Hellman விசை பரிமாற்றத்தைப் பயன்படுத்தும் போது, இந்த பாதுகாப்பு சிறந்த நடைமுறைகளைக் கவனியுங்கள்:

பொருத்தமான விசை அளவுகளைப் பயன்படுத்தவும்: நவீன பயன்பாடுகளுக்கு, குறைந்தது 2048-பிட் முதன்மைகளைப் பயன்படுத்தவும்.
சரிபார்க்கப்பட்ட குழுக்களைப் பயன்படுத்தவும்: எப்போதும் முடிந்தால், RFCகளில் வரையறுக்கப்பட்டுள்ள தரப்படுத்தப்பட்ட குழுக்களைப் பயன்படுத்தவும்.
தனிப்பட்ட விசைகளைப் பாதுகாக்கவும்: பதிவுகள், பிழைத்திருத்த வெளியீடு அல்லது கிளையன்ட்-சைட் குறியீட்டில் தனிப்பட்ட விசைகளை வெளிப்படுத்த வேண்டாம்.
அங்கீகாரத்தைச் சேர்க்கவும்: தூய Diffie-Hellman நடுவர் தாக்குதல்களுக்கு பாதிக்கப்படக்கூடியது. டிஜிட்டல் கையொப்பங்களுடன் ECDHE போன்ற அங்கீகரிக்கப்பட்ட விசை பரிமாற்ற நெறிமுறைகளைப் பயன்படுத்துவதைக் கவனியுங்கள்.
அளவுரு சரிபார்ப்பைச் சரிபார்க்கவும்: அளவுருக்கள் செல்லுபடியாகும் என்பதை உறுதிப்படுத்த எப்போதும் dh.verifyError ஐச் சரிபார்க்கவும்.
குறுகிய கால விசைகளைப் பயன்படுத்தவும்: முன்னோக்கி இரகசியத்தை வழங்க ஒவ்வொரு அமர்வுக்கும் புதிய விசைகளை உருவாக்கவும்.
குறியாக்க விசைகளை சரியாகப் பெறவும்: பகிரப்பட்ட ரகசியத்தை நேரடியாக குறியாக்க விசையாகப் பயன்படுத்த வேண்டாம். HKDF அல்லது PBKDF2 போன்ற விசை பெறுதல் செயல்பாட்டைப் (KDF) பயன்படுத்தவும்.

Comparing with ECDH

Diffie-Hellman (DH) மற்றும் Elliptic Curve Diffie-Hellman (ECDH) இரண்டும் விசை பரிமாற்ற நெறிமுறைகள், ஆனால் ECDH நன்மைகளை வழங்குகிறது:

அம்சம் DiffieHellman ECDH
விசை அளவு பொதுவாக 2048-4096 பிட்கள் பொதுவாக 256-384 பிட்கள்
செயல்திறன் மெதுவாக, அதிக கணக்கீடு தேவை வேகமாக, மிகவும் திறமையானது
பாதுகாப்பு நிலை 2048-பிட் DH ≈ 112-பிட் பாதுகாப்பு 256-பிட் ECDH ≈ 128-பிட் பாதுகாப்பு
நினைவக பயன்பாடு அதிக குறைந்த
நவீன பயன்பாடு புதிய வடிவமைப்புகளில் குறைவாக பொதுவானது புதிய நெறிமுறைகளில் மிகவும் பொதுவானது

💡 முக்கிய குறிப்பு:

அதன் சிறந்த செயல்திறன் மற்றும் சிறிய விசை அளவுகளுக்காக, பெரும்பாலான நவீன பயன்பாடுகளில் ECDH விரும்பப்படுகிறது.

பயிற்சி

Node.js இல் DiffieHellman நிகழ்வை உருவாக்க பயன்படுத்தப்படும் சரியான முறையை தேர்வு செய்யவும்.

crypto.createDH()
✗ தவறு! "crypto.createDH()" என்பது Node.js இல் ஒரு செல்லுபடியாகும் முறை அல்ல
crypto.createDiffieHellman()
✓ சரி! "crypto.createDiffieHellman()" என்பது Node.js இல் DiffieHellman நிகழ்வை உருவாக்க பயன்படும் சரியான முறையாகும்
crypto.makeDiffieHellman()
✗ தவறு! "crypto.makeDiffieHellman()" என்பது Node.js இல் ஒரு செல்லுபடியாகும் முறை அல்ல
crypto.initDiffieHellman()
✗ தவறு! "crypto.initDiffieHellman()" என்பது Node.js இல் ஒரு செல்லுபடியாகும் முறை அல்ல